package co.za.itweb.securedata;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class First extends FragmentActivity {

	
	private static final int ID_SECTORNEWS = 2;
	private static final int ID_FINDUS = 3;
	private static final int ID_ABOUTUS = 4;
	private static final int ID_MYWEB = 5;
	ArrayList<String> updated;
	GridAdapter favadapter;
	FavoriteTask ft;
	static String url = "http://itweb.mobi/_feed/vpo/_load.php?device_os=android&company_folder=securedata&load_config=json";
	
	static ArrayList<RSSFeed> List = new ArrayList<RSSFeed>(0);
	static JSONObject jArray = null;
	
	static String FOLDERNAME = "";
	static JSONObject ICONPACK;
	static String STARTCOLOR = "";
	static String ENDCOLOR = "";
	static String BACKGROUND = "";
	static String BACKGROUNDTEXTCOLOR = "";
	static String LISTTEXTCOLOR = "";
	// ////////////////////////////////////////////////////
	static String mynewsname = "";
	static String sectornewsname = "";
	static String findusname = "";
	static String aboutusname = "";
	static String mywebname = "";
	static String favoritename = "";
	static String refreshname = "";
	static String menuname = "";
	static String backname = "";
	static String twittername = "";
	static String twittervisitedname = "";
	static String addfavoritename = "";
	static String addedfavoritename = "";
	static String emailname = "";
	static String closename = "";

	// ///////////////////////////////////////////////////
	static String TOPBARTEXTCOLOR = "";

	static String ACTIONMENUPATH = "";

	static String ACTIONMENUTEXTCOLOR = "";

	static String ABOUTUS = "";
	static String MYWEB = "";
	static String PATH;
	static String LOGONAME;

	static String SPLASHNAME = "";
	static String SPLASHBACKGROUNDSTART = "";
	static String SPLASHBACKGROUNDEND = "";
	String density = "";

	static String PAGE1TITLE = "";
	static String PAGE2TITLE = "";
	static String PAGE3TITLE = "";
	static String PAGE4TITLE = "";
	static String PAGE5TITLE = "";

	static JSONObject GPSMARKERS;
	static JSONObject INFO;
	
	HorizontalScrollView hsv;
	ImageView topbaricon;
	static String[] titles;
	static String[] images;
	static String[] bigimages;
	static String[] story;
	static String[] published;
	static String[] summary;
	static String[] author;
	String title;

	ListView list;
	LazyAdapter adapter;
	int feedValue = 0;
	int WindowWidth;
	static Dialog dialog;
	ProgressDialog progressDialog;
	RSSFeed feed;
	QuickAction mQuickAction;
	private String[] logoimages;

	static ArrayList<RSSFeed> FavoriteList = new ArrayList<RSSFeed>(0);
	static String COMPANYNAME;
	static String ACTIONMENUBACKGROUNDCOLORSTART;
	static String ACTIONMENUBACKGROUNDCOLOREND;

	static String PAGE4TEXT = "";
	static String PAGE4URL = "";
	static String PAGE5TEXT = "";
	static String PAGE5URL = "";
	public static JSONObject FEEDS=null;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.first);

		if (List.size() == 0 || jArray == null) {

			Intent intent = new Intent(getApplicationContext(), Splash.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(intent, 1);

		} else {
			populate();

		}
	}

	private void populate() {

		topbaricon = (ImageView) findViewById(R.id.title);
		LazyLoadImage icondownloader = new LazyLoadImage(topbaricon);
		Bitmap avatar = icondownloader.getBitmapFromCache(PATH + "images/"
				+ determineDensity() + "/" + LOGONAME);

		if (avatar == null) {
			icondownloader.execute(PATH + "images/" + determineDensity() + "/"
					+ LOGONAME);

		} else {
			topbaricon.setImageBitmap(avatar);
		}

		ActionItem sectornews = new ActionItem(ID_SECTORNEWS, PAGE2TITLE,
				getDrawableFromSD( PAGE2TITLE, getResources()
						.getDrawable(R.drawable.sectornews)));
		ActionItem findus = new ActionItem(ID_FINDUS, PAGE3TITLE,
				getDrawableFromSD(First.findusname,
						getResources().getDrawable(R.drawable.findus)));
		ActionItem aboutus = new ActionItem(ID_ABOUTUS, PAGE4TITLE,
				getDrawableFromSD(First.aboutusname, getResources()
						.getDrawable(R.drawable.findus)));
		ActionItem myweb = new ActionItem(ID_MYWEB, PAGE5TITLE,
				getDrawableFromSD(First.mywebname,
						getResources().getDrawable(R.drawable.myweb)));

		mQuickAction = new QuickAction(getApplicationContext(),
				QuickAction.VERTICAL);

		mQuickAction.addActionItem(sectornews);
		mQuickAction.addActionItem(findus);
		mQuickAction.addActionItem(aboutus);
		mQuickAction.addActionItem(myweb);

		// setup the action item click listener
		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {
					

						if (actionId == ID_SECTORNEWS) {
							Intent intent = new Intent(getApplicationContext(),
									Second.class);

							intent.putExtra("feedid", feedValue);

							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);

						} else if (actionId == ID_FINDUS) {
							Intent intent = new Intent(getApplicationContext(),
									DialogActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);

						} else if (actionId == ID_MYWEB) {
							Intent intent = new Intent(getApplicationContext(),
									MyWeb.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);

						}

						else if (actionId == ID_ABOUTUS) {
							Intent intent = new Intent(getApplicationContext(),
									About.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
						} else {

						}
					}
				});

		mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
				// Toast.makeText(getApplicationContext(), "Ups..dismissed",
				// Toast.LENGTH_SHORT).show();
			}
		});

		LinearLayout backgroundlayout = (LinearLayout) findViewById(R.id.background);
		backgroundlayout.setBackgroundColor(Color.parseColor(BACKGROUND));
		LinearLayout layout = (LinearLayout) findViewById(R.id.cell1);
		if (STARTCOLOR.length() > 3 && ENDCOLOR.length() > 3) {
			int colors[] = { Color.parseColor(STARTCOLOR),
					Color.parseColor(ENDCOLOR) };
			GradientDrawable grad = new GradientDrawable(
					Orientation.TOP_BOTTOM, colors);
			layout.setBackgroundDrawable(grad);
		}

		Button favorites = (Button) findViewById(R.id.cell1).findViewById(
				R.id.favorites);

		favorites.setBackgroundDrawable(getDrawableFromSD(First.favoritename,
				getResources().getDrawable(R.drawable.ic_star)));

		Button refresh = (Button) findViewById(R.id.cell1).findViewById(
				R.id.refresh);

		refresh.setBackgroundDrawable(getDrawableFromSD(First.refreshname,
				getResources().getDrawable(R.drawable.ic_refresh)));

		TextView titletext = (TextView) findViewById(R.id.page);
		titletext.setText(PAGE1TITLE);
		titletext.setTextColor(Color.parseColor(LISTTEXTCOLOR));
		titletext.setPaintFlags(titletext.getPaintFlags()
				| Paint.UNDERLINE_TEXT_FLAG);

		Button menu = (Button) findViewById(R.id.cell1).findViewById(R.id.menu);
		menu.setBackgroundDrawable(getDrawableFromSD(First.menuname,
				getResources().getDrawable(R.drawable.menu)));

		menu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				mQuickAction.show(v);
				mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);

			}
		});

		favorites.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog = new Dialog(First.this);
				dialog.setContentView(R.layout.dialog_favorites);
				dialog.setTitle("SecureData Favorites");
				dialog.setCancelable(true);
				Button buttonclose = (Button) dialog
						.findViewById(R.id.closebutton);
				buttonclose.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {

						dialog.dismiss();
					}
				});
				dialog.show();
				showFavourites();
			}
		});

		refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(First.this, Refresh.class);
				startActivityForResult(intent, 2);

			}
		});

		if (List.size() == 0) {
			Toast.makeText(getApplicationContext(), "Feed is not loaded",
					Toast.LENGTH_LONG).show();
			Intent intent1 = new Intent(getApplicationContext(),
					SingleNews.class);
			intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent1);
		} else {

			titles = new String[List.get(feedValue)._itemlist.size()];
			images = new String[List.get(feedValue)._itemlist.size()];
			bigimages = new String[List.get(feedValue)._itemlist.size()];
			logoimages = new String[List.get(feedValue)._itemlist.size()];
			story = new String[List.get(feedValue)._itemlist.size()];
			published = new String[List.get(feedValue)._itemlist.size()];
			summary = new String[List.get(feedValue)._itemlist.size()];
			author = new String[List.get(feedValue)._itemlist.size()];

			for (int i = 0; i < List.get(feedValue)._itemlist.size(); i++) {
				if (List.get(feedValue)._itemlist.get(i).getTitle() != null) {
					titles[i] = List.get(feedValue)._itemlist.get(i).getTitle();
				} else {
					titles[i] = "";
				}
				if (List.get(feedValue)._itemlist.get(i).getImage() != null) {
					images[i] = List.get(feedValue)._itemlist.get(i).getImage();
				} else {
					images[i] = "";
				}

				if (List.get(feedValue)._itemlist.get(i).getbigImage() != null) {
					bigimages[i] = List.get(feedValue)._itemlist.get(i)
							.getbigImage();
				} else {
					bigimages[i] = "";
				}
				if (List.get(feedValue)._itemlist.get(i).getLogoImage() != null) {
					logoimages[i] = List.get(feedValue)._itemlist.get(i)
							.getLogoImage();
				} else {
					logoimages[i] = "";
				}
				if (List.get(feedValue)._itemlist.get(i).getStory() != null) {
					story[i] = List.get(feedValue)._itemlist.get(i).getStory()
							.toString();
				} else {
					story[i] = "";
				}
				if (List.get(feedValue)._itemlist.get(i).getpubDate() != null) {
					published[i] = List.get(feedValue)._itemlist.get(i)
							.getpubDate();
				} else {
					published[i] = "";
				}
				if (List.get(feedValue)._itemlist.get(i).getSummary() != null) {
					summary[i] = List.get(feedValue)._itemlist.get(i)
							.getSummary();
				} else {
					summary[i] = "";
				}
				if (List.get(feedValue)._itemlist.get(i).getAuthor() != null) {
					author[i] = List.get(feedValue)._itemlist.get(i)
							.getAuthor();
				} else {
					author[i] = "";
				}
			}

			list = (ListView) findViewById(R.id.list);

			adapter = new LazyAdapter(First.this, images,logoimages);
			list.setAdapter(adapter);

			list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					Intent intent = new Intent(getApplicationContext(),
							SingleNews.class);
					intent.putExtra("id", position);
					intent.putExtra("feedid", feedValue);

					startActivity(intent);
				}
			});

		}

	}

	
	public Drawable getDrawableFromSD(String imagename, Drawable defaultdrawable) {
		File path = new File(Environment.getExternalStorageDirectory() + "/"
				+ FOLDERNAME + "/" + imagename);
		if (path.exists()) {
			try {
				Bitmap bitmapImage = BitmapFactory.decodeFile(Environment
						.getExternalStorageDirectory()
						+ "/"
						+ FOLDERNAME
						+ "/"
						+ imagename);
				Drawable bgrImage;
				bgrImage = new BitmapDrawable(getResources(), bitmapImage);

				return bgrImage;

			} catch (Exception ex) {
				//System.out.println(ex.toString());
				return defaultdrawable;
			}
		} else {
			return defaultdrawable;
		}
	}

	public String determineDensity() {
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density = "ldpi";
			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density = "mdpi";
			break;
		case DisplayMetrics.DENSITY_HIGH:
			density = "hdpi";
			break;
		case DisplayMetrics.DENSITY_XHIGH:
			density = "xdpi";
			break;
		}
		return density;
	}

	@SuppressLint("WorldReadableFiles")
	private void showFavourites() {
		if (dialog.isShowing()) {
			String[] favorites = null;
			ListView listView2 = (ListView) dialog
					.findViewById(R.id.myfavorites);

			SharedPreferences myPrefs = getSharedPreferences(
					SingleNews.PREFS_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweblite.fav", "title");
			prefName = prefName.replaceAll("/", "");

		//	System.out.println("////////////////////////////////////////////////////////////////////////"+ prefName);
			JSONArray dat;
			try {
				dat = new JSONArray(prefName);

				favorites = new String[dat.length()];
				
				for (int t = 0; t < dat.length(); t++) {
					try {
						String obj = dat.getJSONObject(t).getString("title")
								+ "|" + dat.getJSONObject(t).getString("id")
								+ "|" + dat.getJSONObject(t).getString("feed");
						favorites[t] = obj;
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			if (favorites != null) {
				favadapter = new GridAdapter(First.this, favorites);
				listView2.setAdapter(favadapter);

			} else {
				Toast.makeText(getApplicationContext(), "No feeds added",
						Toast.LENGTH_SHORT).show();
				dialog.dismiss();
			}

		}

	}

	public class GridAdapter extends BaseAdapter {
		String[] separated;
		private FragmentActivity activity;
		public String[] data;
		public LayoutInflater inflater = null;
		public TextView titletext;
		public ImageLoader imageLoader;
		ArrayList<String> list = new ArrayList<String>();
		JSONArray jsonArray;

		public GridAdapter(FragmentActivity a, String[] d) {
			activity = a;
			data = d;
			imageLoader = new ImageLoader(activity.getApplicationContext());
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		}

		public int getCount() {
			return data.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("WorldReadableFiles")
		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;
			if (convertView == null)
				vi = inflater.inflate(R.layout.gridbanners, null);
			separated = data[position].split("\\|");
			titletext = (TextView) vi.findViewById(R.id.texttitle);
			ImageButton erasebutton = (ImageButton) vi
					.findViewById(R.id.erasebutton);
			titletext.setText(separated[0]);
			titletext.setTag(separated[1]);

			titletext.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					ft = new FavoriteTask(First.this, v.getTag().toString());
					ft.execute();
					First.dialog.dismiss();
					// Uri uri =
					// Uri.parse("http://www.itweb.co.za/index.php?option=com_content&view=article&id="+v.getTag());
					// Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					// startActivity(intent);
				}
			});
			erasebutton.setTag(position);

			erasebutton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					JSONArray JArray;
					try {
						SharedPreferences myPrefs = getSharedPreferences(
								SingleNews.PREFS_NAME, MODE_WORLD_READABLE);
						String prefName = myPrefs.getString(
								"co.za.itweblite.fav", "title");

						JArray = new JSONArray(prefName);

						List<Object> list = new ArrayList<Object>();

						for (int i = 0; i < JArray.length(); i++) {
							list.add(JArray.get(i));
						}

						if (list.size() > 0) {
							for (int i = 0; i < list.size(); i++) {
								if (Integer.parseInt(v.getTag().toString()) == i) {
									list.remove(i);
								}
							}

							JSONArray jsArray = new JSONArray(list);

							StringBuilder buf = new StringBuilder();

							buf.append(jsArray).append("\n");

							SharedPreferences settings = getSharedPreferences(
									SingleNews.PREFS_NAME, 0);
							SharedPreferences.Editor editor = settings.edit();
							editor.clear();

							// SharedPreferences.Editor editor =
							// getSharedPreferences(MODE_WORLD_READABLE).edit();
							editor.putString("co.za.itweblite.fav",
									buf.toString());
							editor.commit();
							showFavourites();
						}

					} catch (JSONException e) {
						e.printStackTrace();
						Toast.makeText(
								getApplicationContext(),
								"Sorry there has been a problem with erasing your favorite news...",
								Toast.LENGTH_SHORT).show();
					}

				}

			});

			return vi;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		System.out.println("RESULT CODE" + resultCode + " REQUEST CODE "
				+ requestCode + " DATA " + data);

		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {
				try {

					populate();
					Toast.makeText(getApplicationContext(),
							"News are refreshed...", Toast.LENGTH_SHORT).show();
				} catch (Exception ex) {

					Toast.makeText(getApplicationContext(),
							"There was a problem, please try again...",
							Toast.LENGTH_SHORT).show();
					//System.out.println(ex.toString()+ "**************************************************");
				}
			}

			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(
						getApplicationContext(),
						"There has been a mistake while refreshing news feeds..., please try again",
						Toast.LENGTH_SHORT).show();
				finish();

			}

		}

		if (requestCode == 2) {

			if (resultCode == RESULT_OK) {
				adapter.notifyDataSetChanged();
				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();
				adapter.notifyDataSetChanged();
			}

			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"There was mistake while refreshing...",
						Toast.LENGTH_SHORT).show();

			}
		}

	}

	

	@Override
	protected void onPause() {
		

		if (mQuickAction != null && mQuickAction.mWindow.isShowing()) {
			mQuickAction.dismiss();

		}

		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		overridePendingTransition(R.anim.hold, R.anim.push_out_to_left);
		super.onPause();
	}

	private class FavoriteTask extends AsyncTask<Void, Integer, Void> {
		RSSFeed favoriteFeed;
		ProgressDialog dialog;
		
		int id;

		public FavoriteTask(First activity, String articleId) {
			
			this.id = Integer.parseInt(articleId.toString());

			dialog = new ProgressDialog(activity);
			dialog.setMessage("Loading Favorite...");
			//dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					ft.cancel(true);
					Toast.makeText(getApplicationContext(),
							"Loading canceled...", Toast.LENGTH_SHORT).show();
				}
			});
			dialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			FavoriteList.clear();
			
			favoriteFeed = getFeed2("http://itweb.mobi/feed/ios-v2.php/?source=ipad&tag=article&id="
					+ id);

			if (favoriteFeed != null) {
				FavoriteList.add(favoriteFeed);
				publishProgress();
				if (isCancelled()) {
					FavoriteList.clear();
					if (dialog.isShowing()) {
						dialog.dismiss();
					}

					return null;
				}

			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (FavoriteList.size() == 1) {
				//System.out.println(FavoriteList.get(0)._itemlist.get(0).getTitle() + "/////////////////////////////");
				Intent intent = new Intent(getApplicationContext(),
						SingleFavorite.class);
				intent.putExtra("id", 0);
				intent.putExtra("feedid", 0);
				startActivity(intent);
			}

		}

	}

	public static RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			//System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			//System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ ee.toString());
			return null;
		}
	}

	public static RSSFeed getFeed2(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler2 theRssHandler = new RSSHandler2();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

		//	System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
		//	System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ ee.toString());
			return null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			File storagePathdelete = new File(Environment.getExternalStorageDirectory().getPath()+"/"+FOLDERNAME+"/");
			
			deleteAllIcons(storagePathdelete);
		//	System.out.println(Environment.getExternalStorageDirectory().getPath()+"/"+FOLDERNAME+"/");
			List.clear();
			jArray = null;
			FOLDERNAME = "";
			ICONPACK = null;
			STARTCOLOR = "";
			ENDCOLOR = "";
			BACKGROUND = "";
			BACKGROUNDTEXTCOLOR = "";
			LISTTEXTCOLOR = "";
			TOPBARTEXTCOLOR = "";
			ACTIONMENUPATH = "";
			ACTIONMENUBACKGROUNDCOLORSTART = "";
			ACTIONMENUBACKGROUNDCOLOREND = "";
			ACTIONMENUTEXTCOLOR = "";
			PAGE2TITLE = "";
			PAGE3TITLE = "";
			PAGE4TITLE = "";
			PAGE5TITLE = "";
			PAGE4TEXT = "";
			PAGE4URL = "";
			PAGE5TEXT = "";
			PAGE5URL = "";
			ABOUTUS = "";
			MYWEB = "";
			PATH = "";
			LOGONAME = "";
			GPSMARKERS = null;
			COMPANYNAME = "";
			INFO = null;
			closename = "";
			mynewsname = "";
			sectornewsname = "";
			findusname = "";
			aboutusname = "";
			mywebname = "";
			favoritename = "";
			refreshname = "";
			menuname = "";
			backname = "";
			twittername = "";
			twittervisitedname = "";
			addfavoritename = "";
			addedfavoritename = "";
			emailname = "";
			SPLASHNAME = "";
			SPLASHBACKGROUNDSTART = "";
			SPLASHBACKGROUNDEND = "";
			density = "";
			titles = null;
			images = null;
			bigimages = null;
			story = null;
			published = null;
			summary = null;
			author = null;
			
			finish();

		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		File storagePathdelete = new File(Environment.getExternalStorageDirectory().getPath() + "/" + FOLDERNAME+"/");
		deleteAllIcons(storagePathdelete);
		List.clear();
		jArray = null;
		FOLDERNAME = "";
		ICONPACK = null;
		STARTCOLOR = "";
		ENDCOLOR = "";
		BACKGROUND = "";
		BACKGROUNDTEXTCOLOR = "";
		LISTTEXTCOLOR = "";
		TOPBARTEXTCOLOR = "";
		ACTIONMENUPATH = "";
		ACTIONMENUBACKGROUNDCOLORSTART = "";
		ACTIONMENUBACKGROUNDCOLOREND = "";
		ACTIONMENUTEXTCOLOR = "";
		PAGE1TITLE = "";
		PAGE2TITLE = "";
		PAGE3TITLE = "";
		PAGE4TITLE = "";
		PAGE5TITLE = "";
		PAGE5TEXT = "";
		PAGE5URL = "";
		ABOUTUS = "";
		MYWEB = "";
		PATH = "";
		LOGONAME = "";
		

		SPLASHNAME = "";
		SPLASHBACKGROUNDSTART = "";
		SPLASHBACKGROUNDEND = "";

		GPSMARKERS = null;
		COMPANYNAME = "";
		INFO = null;
		mynewsname = "";
		sectornewsname = "";
		findusname = "";
		aboutusname = "";
		mywebname = "";
		favoritename = "";
		refreshname = "";
		menuname = "";
		backname = "";
		twittername = "";
		twittervisitedname = "";
		addfavoritename = "";
		addedfavoritename = "";
		emailname = "";
		closename="";
		density = "";
		titles = null;
		images = null;
		bigimages = null;
		story = null;
		published = null;
		summary = null;
		author = null;
		
		
		finish();
		return;
	}

	public void deleteAllIcons(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				new File(dir, children[i]).delete();
				
			}
		}
	}

}
